package com.example.suhui_test.customview;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import com.example.suhui_test.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 流式布局ViewGroup
 * 知识点：
 * 1. 自定义ViewGroup - 继承ViewGroup实现自定义布局管理器
 * 2. onMeasure方法 - 测量子View和自身尺寸
 * 3. onLayout方法 - 布局子View的位置
 * 4. MeasureSpec的使用 - 理解测量模式
 * 5. LayoutParams的处理 - 处理子View的布局参数
 * 6. 多行布局算法 - 自动换行逻辑
 * 7. 间距处理 - 水平和垂直间距
 */
public class FlowLayout extends ViewGroup {
    
    // 默认间距
    private static final int DEFAULT_HORIZONTAL_SPACING = 10;
    private static final int DEFAULT_VERTICAL_SPACING = 10;
    private static final int DEFAULT_MAX_LINES = Integer.MAX_VALUE;
    
    // 自定义属性
    private int horizontalSpacing;
    private int verticalSpacing;
    private int maxLines;
    
    // 布局相关
    private List<List<View>> allLines; // 所有行的View列表
    private List<Integer> lineHeights; // 每行的高度

    public FlowLayout(Context context) {
        this(context, null);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttributes(context, attrs);
        initLayout();
    }

    /**
     * 初始化自定义属性
     */
    private void initAttributes(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FlowLayout);
        
        horizontalSpacing = (int) typedArray.getDimension(
            R.styleable.FlowLayout_horizontalSpacing, 
            DEFAULT_HORIZONTAL_SPACING
        );
        verticalSpacing = (int) typedArray.getDimension(
            R.styleable.FlowLayout_verticalSpacing, 
            DEFAULT_VERTICAL_SPACING
        );
        maxLines = typedArray.getInteger(
            R.styleable.FlowLayout_maxLines, 
            DEFAULT_MAX_LINES
        );
        
        typedArray.recycle();
    }

    /**
     * 初始化布局数据结构
     */
    private void initLayout() {
        allLines = new ArrayList<>();
        lineHeights = new ArrayList<>();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 清空之前的数据
        allLines.clear();
        lineHeights.clear();
        
        // 获取可用宽度
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        
        // 计算可用宽度（减去padding）
        int availableWidth = widthSize - getPaddingLeft() - getPaddingRight();
        
        // 当前行的View列表和尺寸
        List<View> currentLine = new ArrayList<>();
        int currentLineWidth = 0;
        int currentLineHeight = 0;
        
        // 总尺寸
        int totalWidth = 0;
        int totalHeight = getPaddingTop() + getPaddingBottom();
        
        // 遍历所有子View
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == GONE) {
                continue;
            }
            
            // 测量子View
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();
            
            // 检查是否需要换行
            boolean needNewLine = false;
            if (currentLine.isEmpty()) {
                // 第一个View，直接添加
                needNewLine = false;
            } else {
                // 计算加上当前View后的宽度
                int lineWidthWithChild = currentLineWidth + horizontalSpacing + childWidth;
                if (lineWidthWithChild > availableWidth) {
                    needNewLine = true;
                }
            }
            
            // 检查是否超过最大行数
            if (needNewLine && allLines.size() >= maxLines) {
                break; // 超过最大行数，停止添加
            }
            
            if (needNewLine) {
                // 保存当前行
                allLines.add(new ArrayList<>(currentLine));
                lineHeights.add(currentLineHeight);
                
                // 更新总尺寸
                totalWidth = Math.max(totalWidth, currentLineWidth);
                if (!allLines.isEmpty()) {
                    totalHeight += verticalSpacing;
                }
                totalHeight += currentLineHeight;
                
                // 开始新行
                currentLine.clear();
                currentLineWidth = 0;
                currentLineHeight = 0;
            }
            
            // 添加到当前行
            currentLine.add(child);
            if (currentLine.size() == 1) {
                currentLineWidth = childWidth;
            } else {
                currentLineWidth += horizontalSpacing + childWidth;
            }
            currentLineHeight = Math.max(currentLineHeight, childHeight);
        }
        
        // 保存最后一行
        if (!currentLine.isEmpty()) {
            allLines.add(currentLine);
            lineHeights.add(currentLineHeight);
            totalWidth = Math.max(totalWidth, currentLineWidth);
            if (allLines.size() > 1) {
                totalHeight += verticalSpacing;
            }
            totalHeight += currentLineHeight;
        }
        
        // 加上padding
        totalWidth += getPaddingLeft() + getPaddingRight();
        
        // 确定最终尺寸
        int finalWidth = widthMode == MeasureSpec.EXACTLY ? widthSize : totalWidth;
        int finalHeight = heightMode == MeasureSpec.EXACTLY ? heightSize : totalHeight;
        
        setMeasuredDimension(finalWidth, finalHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();
        
        int currentTop = paddingTop;
        
        // 布局每一行
        for (int i = 0; i < allLines.size(); i++) {
            List<View> line = allLines.get(i);
            int lineHeight = lineHeights.get(i);
            
            int currentLeft = paddingLeft;
            
            // 布局当前行的每个View
            for (View child : line) {
                int childWidth = child.getMeasuredWidth();
                int childHeight = child.getMeasuredHeight();
                
                // 垂直居中对齐
                int childTop = currentTop + (lineHeight - childHeight) / 2;
                int childBottom = childTop + childHeight;
                int childRight = currentLeft + childWidth;
                
                // 布局子View
                child.layout(currentLeft, childTop, childRight, childBottom);
                
                // 移动到下一个位置
                currentLeft += childWidth + horizontalSpacing;
            }
            
            // 移动到下一行
            currentTop += lineHeight + verticalSpacing;
        }
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    }

    @Override
    protected LayoutParams generateLayoutParams(LayoutParams p) {
        return new MarginLayoutParams(p);
    }

    @Override
    protected boolean checkLayoutParams(LayoutParams p) {
        return p instanceof MarginLayoutParams;
    }

    /**
     * 设置水平间距
     */
    public void setHorizontalSpacing(int spacing) {
        if (this.horizontalSpacing != spacing) {
            this.horizontalSpacing = spacing;
            requestLayout();
        }
    }

    /**
     * 设置垂直间距
     */
    public void setVerticalSpacing(int spacing) {
        if (this.verticalSpacing != spacing) {
            this.verticalSpacing = spacing;
            requestLayout();
        }
    }

    /**
     * 设置最大行数
     */
    public void setMaxLines(int maxLines) {
        if (this.maxLines != maxLines) {
            this.maxLines = maxLines;
            requestLayout();
        }
    }

    /**
     * 获取水平间距
     */
    public int getHorizontalSpacing() {
        return horizontalSpacing;
    }

    /**
     * 获取垂直间距
     */
    public int getVerticalSpacing() {
        return verticalSpacing;
    }

    /**
     * 获取最大行数
     */
    public int getMaxLines() {
        return maxLines;
    }

    /**
     * 获取当前行数
     */
    public int getLineCount() {
        return allLines.size();
    }

    /**
     * 获取指定行的View数量
     */
    public int getLineViewCount(int line) {
        if (line >= 0 && line < allLines.size()) {
            return allLines.get(line).size();
        }
        return 0;
    }
}